package com.feimt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feimt.common.CustomException;
import com.feimt.mapper.CategoryMapper;
import com.feimt.pojo.Category;
import com.feimt.pojo.Dish;
import com.feimt.pojo.Setmeal;
import com.feimt.service.CategoryService;
import com.feimt.service.DishService;
import com.feimt.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 宋孟林
 * @description
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private DishService dishService;
    private SetmealService setMealService;

    @Autowired
    public CategoryServiceImpl(DishService dishService, SetmealService setMealService) {
        this.dishService = dishService;
        this.setMealService = setMealService;
    }

    /**
     * 自定义根据id删除分类，定义逻辑：先查询此种类是否和菜品相关联，如果关联抛出异常不能删除
     * 再查询此种类是否和套餐关联如果关联抛出异常，如果这两种异常都没有抛出调用还是调用底层根据id删除分类的方法
     * @param id 根据id来删除
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(wrapper);
        if(count1 > 0){
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Setmeal::getCategoryId,id);
        int count2 = setMealService.count(wrapper1);
        if(count2 > 0){
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        this.removeById(id);
    }
}
